package com.example.demo.aspect;

import com.alibaba.fastjson.JSON;
import com.example.demo.annotation.RequestAuthCheck;
import com.example.demo.entity.Menu;
import com.example.demo.enums.StatusCodeEnum;
import com.example.demo.exception.CustomException;
import com.example.demo.util.AuthContextUtil;
import com.example.demo.util.NormalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @description：校验接口权限切面类.
 * @author：lw
 * @create_time：2024/1/19
 **/

@Aspect
@Component
@Slf4j
//@Order(value = 1)     // 设定执行顺序，序号小的先执行
public class RequestAuthCheckAspect {

    @Before(value = "@annotation(requestAuthCheck)")
    public void doBefore(RequestAuthCheck requestAuthCheck){
        Map<String, String> map =AuthContextUtil.get().getNameToMenuMap();
        String menuName=requestAuthCheck.menuName();
        String action=requestAuthCheck.action();
        if(map.get(menuName)==null) throw new CustomException(StatusCodeEnum.noAuth);
        String actions= JSON.parseObject(map.get(menuName),Menu.class).getActions();
        if(NormalUtil.isEmpty(actions)) throw new CustomException(StatusCodeEnum.noAuth);
        List<String> actionList=Arrays.asList(actions.split(","));
        if(!actionList.contains(action)) throw new CustomException(StatusCodeEnum.noAuth);
    }
}
